package com.tbvtc.agriculturalcreditchainserver2025.utils.huawei;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tbvtc.agriculturalcreditchainserver2025.constant.IotConstant;
import com.tbvtc.agriculturalcreditchainserver2025.utils.http.HttpConstant;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import static com.tbvtc.agriculturalcreditchainserver2025.constant.HwCloudIotConstant.*;


@Component
public class HwCloudIot {

    @Resource(name = "TredisTemplate")
    private RedisTemplate<String, String> redisTemplate;

    // 获取AccessToken
    public String getAccessToken() throws Exception {

        String token = redisTemplate.opsForValue().get("HUAWEI::accessToken");
        if (token != null) {
            return token;
        }

        String url = "https://iam.cn-north-4.myhuaweicloud.com/v3/auth/tokens";

        JSONObject payload = new JSONObject();
        JSONObject auth = new JSONObject();
        JSONObject identity = new JSONObject();
        JSONObject hwAkSk = new JSONObject();
        JSONObject access = new JSONObject();
        JSONObject secret = new JSONObject();
        JSONObject scope = new JSONObject();
        JSONObject project = new JSONObject();

        access.put("key", AK);
        secret.put("key", SK);
        hwAkSk.put("access", access);
        hwAkSk.put("secret", secret);
        identity.put("methods", Arrays.asList("hw_ak_sk"));
        identity.put("hw_ak_sk", hwAkSk);
        project.put("name", "cn-east-3");
        scope.put("project", project);
        auth.put("identity", identity);
        auth.put("scope", scope);
        payload.put("auth", auth);

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");

        HttpResult result = sendHttpRequest(url, "POST", headers, payload.toJSONString());

        if (result.responseCode == 201) {
            String afterToken = result.headers.get("x-subject-token");
            redisTemplate.opsForValue().set("HUAWEI::accessToken", afterToken, 1, java.util.concurrent.TimeUnit.HOURS);
            return afterToken;
        } else {
            throw new Exception("Failed to get token: " + result.response);
        }
    }

    /**
     * 获取光照强度
     *
     * @return
     * @throws Exception
     */
    public int getIlluminationValue() throws Exception {

        String url = String.format("https://d3c942cb24.st1.iotda-app.cn-north-4.myhuaweicloud.com"
                        + IotConstant.URL
                , PROJECT_ID, GetGuangValue_ID
        );
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put(HttpConstant.AuthToken, getAccessToken());
        hashMap.put(HttpConstant.CONTENTYPE, HttpConstant.CONTENTYPEVALUE);
        HttpResult httpResult = sendHttpRequest(url, "GET", hashMap, null);
        return getIllHttpResult(httpResult);
    }

    /**
     * 获取温湿度
     *
     * @return
     * @throws Exception
     */
    public Map<String, Double> getTemAndHumInfo() throws Exception {
        //构建华为云平台请求url
        String url = getTemHumUrl(
                "d3c942cb24.st1.iotda-app.cn-north-4.myhuaweicloud.com",
                TEM_HUM_DEVICE_ID);
        //构建请求体
        HashMap<String, String> headers = new HashMap<>();
        headers.put(HttpConstant.AuthToken,getAccessToken());
        headers.put(HttpConstant.CONTENTYPEVALUE,HttpConstant.CONTENTYPEVALUE);
        //get请求
        HttpResult httpResult = sendHttpRequest(url, "GET", headers, null);
        return ToMap(httpResult);
    }


    // 获取土壤湿度（百分比）
    public double getSoilMoistureInfo() throws Exception {
        String url = String.format(
                "https://d3c942cb24.st1.iotda-app.cn-north-4.myhuaweicloud.com:443/v5/iot/%s/devices/%s/shadow",
                PROJECT_ID, SOIL_MOISTURE_ID);

        Map<String, String> headers = new HashMap<>();
        headers.put("X-Auth-Token", getAccessToken());
        headers.put("Content-Type", "application/json");

        HttpResult result = sendHttpRequest(url, "GET", headers, null);

        JSONObject json = JSON.parseObject(result.response);
        JSONArray shadow = json.getJSONArray("shadow");
        JSONObject firstShadow = shadow.getJSONObject(0);
        JSONObject reported = firstShadow.getJSONObject("reported");
        JSONObject properties = reported.getJSONObject("properties");
        int rawValue = properties.getInteger("humidity");

        // 转换量程 (500~1200 → 0%~100%)
        double percentage = ((rawValue - 500) / 700.0) * 100;
        percentage = Math.max(0, Math.min(100, percentage)); // 确保在0-100范围内
        return Math.round(percentage * 10) / 10.0; // 保留1位小数
    }

    // 获取水温
    public double getWaterTemperature() throws Exception {
        String url = String.format(
                "https://d3c942cb24.st1.iotda-app.cn-north-4.myhuaweicloud.com:443/v5/iot/%s/devices/%s/shadow",
                PROJECT_ID, WATER_DEVICE_ID);

        Map<String, String> headers = new HashMap<>();
        headers.put("X-Auth-Token", getAccessToken());
        headers.put("Content-Type", "application/json");

        HttpResult result = sendHttpRequest(url, "GET", headers, null);

        JSONObject json = JSON.parseObject(result.response);
        JSONArray shadow = json.getJSONArray("shadow");
        JSONObject firstShadow = shadow.getJSONObject(0);
        JSONObject reported = firstShadow.getJSONObject("reported");
        JSONObject properties = reported.getJSONObject("properties");
        return properties.getDouble("temperature");
    }


    // 获取风扇状态
    public String getFanStatus() throws Exception {
        String url = String.format(
                "https://d3c942cb24.st1.iotda-app.cn-north-4.myhuaweicloud.com:443/v5/iot/%s/devices/%s/shadow",
                PROJECT_ID, FAN_DEVICE_ID);

        Map<String, String> headers = new HashMap<>();
        headers.put("X-Auth-Token", getAccessToken());
        headers.put("Content-Type", "application/json");

        HttpResult result = sendHttpRequest(url, "GET", headers, null);

        JSONObject json = JSON.parseObject(result.response);
        JSONArray shadow = json.getJSONArray("shadow");
        JSONObject firstShadow = shadow.getJSONObject(0);
        JSONObject reported = firstShadow.getJSONObject("reported");
        JSONObject properties = reported.getJSONObject("properties");
        return properties.getString("flagValue");
    }

    // 下发风扇控制命令
    public String sendFanCommand(String flag) throws Exception {
        String url = String.format(
                "https://d3c942cb24.st1.iotda-app.cn-north-4.myhuaweicloud.com:443/v5/iot/%s/devices/%s/commands",
                PROJECT_ID, FAN_DEVICE_ID);

        Map<String, String> headers = new HashMap<>();
        headers.put("X-Auth-Token", getAccessToken());
        headers.put("Content-Type", "application/json");

        JSONObject payload = new JSONObject();
        payload.put("service_id", "Fan");
        payload.put("command_name", "FanFlag");

        JSONObject paras = new JSONObject();
        paras.put("flagValue", flag);
        payload.put("paras", paras);

        HttpResult result = sendHttpRequest(url, "POST", headers, payload.toJSONString());
        return result.response;
    }

    // 下发农药水泵控制命令
    public String sendWaterpumpCommand(String flag) throws Exception {
        String url = String.format(
                "https://d3c942cb24.st1.iotda-app.cn-north-4.myhuaweicloud.com:443/v5/iot/%s/devices/%s/commands",
                PROJECT_ID, PESTICIDEDEVICE_ID);

        Map<String, String> headers = new HashMap<>();
        headers.put("X-Auth-Token", getAccessToken());
        headers.put("Content-Type", "application/json");

        JSONObject payload = new JSONObject();
        payload.put("service_id", "waterpump");
        payload.put("command_name", "FanFlag");

        JSONObject paras = new JSONObject();
        paras.put("flagValue", flag);
        payload.put("paras", paras);

        HttpResult result = sendHttpRequest(url, "POST", headers, payload.toJSONString());
        return result.response;
    }

    // 获取农药水泵状态
    public String getWaterpumpStatus() throws Exception {
        String url = String.format(
                "https://d3c942cb24.st1.iotda-app.cn-north-4.myhuaweicloud.com:443/v5/iot/%s/devices/%s/shadow",
                PROJECT_ID, PESTICIDEDEVICE_ID);

        Map<String, String> headers = new HashMap<>();
        headers.put("X-Auth-Token", getAccessToken());
        headers.put("Content-Type", "application/json");

        HttpResult result = sendHttpRequest(url, "GET", headers, null);

        JSONObject json = JSON.parseObject(result.response);
        JSONArray shadow = json.getJSONArray("shadow");
        JSONObject firstShadow = shadow.getJSONObject(0);
        JSONObject reported = firstShadow.getJSONObject("reported");
        JSONObject properties = reported.getJSONObject("properties");
        return properties.getString("flagValue");
    }


    // 下发LED灯命令
    public String sendLivingLedCommand(String color) throws Exception {
        String url = String.format(
                "https://d3c942cb24.st1.iotda-app.cn-north-4.myhuaweicloud.com:443/v5/iot/%s/devices/%s/commands",
                PROJECT_ID, LIVING_LED_DEVICE_ID);

        Map<String, String> headers = new HashMap<>();
        headers.put("X-Auth-Q1`", getAccessToken());
        headers.put("Content-Type", "application/json");

        JSONObject payload = new JSONObject();
        payload.put("service_id", "Livingroom");
        payload.put("command_name", "color_light");

        JSONObject paras = new JSONObject();
        paras.put("color", color);
        payload.put("paras", paras);

        HttpResult result = sendHttpRequest(url, "POST", headers, payload.toJSONString());
        return result.response;
    }

    // 通用HTTP请求方法
    private HttpResult sendHttpRequest(String urlStr, String method,
                                       Map<String, String> headers, String body) throws Exception {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod(method);
        conn.setConnectTimeout(60000);
        conn.setReadTimeout(60000);

        // 设置请求头
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            conn.setRequestProperty(entry.getKey(), entry.getValue());
        }

        // 处理POST请求体
        if (body != null && ("POST".equals(method) || "PUT".equals(method))) {
            conn.setDoOutput(true);
            try (OutputStream os = conn.getOutputStream()) {
                byte[] input = body.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }
        }

        // 获取响应代码
        int responseCode = conn.getResponseCode();

        // 读取响应
        StringBuilder response = new StringBuilder();
        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
            String line;
            while ((line = br.readLine()) != null) {
                response.append(line);
            }
        }

        // 收集响应头
        Map<String, String> responseHeaders = new HashMap<>();
        for (String key : conn.getHeaderFields().keySet()) {
            if (key != null) {
                responseHeaders.put(key.toLowerCase(), conn.getHeaderField(key));
            }
        }

        conn.disconnect();
        return new HttpResult(responseCode, response.toString(), responseHeaders);
    }

    // HTTP响应封装类
    private static class HttpResult {
        int responseCode;
        String response;
        Map<String, String> headers;

        public HttpResult(int responseCode, String response, Map<String, String> headers) {
            this.responseCode = responseCode;
            this.response = response;
            this.headers = headers;
        }
    }

    public int getIllHttpResult(HttpResult result) {
        JSONObject json = JSON.parseObject(result.response);
        JSONArray shadow = json.getJSONArray("shadow");
        JSONObject firstShadow = shadow.getJSONObject(0);
        JSONObject reported = firstShadow.getJSONObject("reported");
        JSONObject properties = reported.getJSONObject("properties");
        return properties.getInteger("illumination");
    }

    public Map<String, Double> ToMap(HttpResult result) {
        JSONObject json = JSON.parseObject(result.response);
        JSONArray shadow = json.getJSONArray("shadow");
        JSONObject firstShadow = shadow.getJSONObject(0);
        JSONObject reported = firstShadow.getJSONObject("reported");
        JSONObject properties = reported.getJSONObject("properties");

        Map<String, Double> resultMap = new HashMap<>();
        resultMap.put("temperature", properties.getDouble("temperature"));
        resultMap.put("humidity", properties.getDouble("humidity"));
        return resultMap;
    }

    public String getTemHumUrl(String url, String deviceId) {
        return String.format("https://" + url + IotConstant.URL
                , PROJECT_ID, deviceId
        );
    }
}